import React from 'react';
import { Box, Text } from 'ink';
import { Message, ThemeConfig } from '../types';
import MarkdownRenderer from './MarkdownRenderer';
import ThinkingBox from './ThinkingBox';
import ToolUsageIndicator from './ToolUsageIndicator';

interface MessageItemProps {
  message: Message;
  theme: ThemeConfig;
}

const MessageItem: React.FC<MessageItemProps> = ({ message, theme }) => {
  const getMessageColor = () => {
    if (message.status === 'error') return theme.errorMessage;
    return message.role === 'user' ? theme.userMessage : theme.aiMessage;
  };

  const getMessagePrefix = () => {
    if (message.role === 'user') return 'You: ';
    if (message.status === 'sending') return 'AI (正在输入...): ';
    if (message.status === 'interrupted') return 'AI (已中断): ';
    return 'AI: ';
  };

  const formatTimestamp = (timestamp: Date) => {
    return timestamp.toLocaleTimeString('zh-CN', { 
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };

  return (
    <Box flexDirection="column" marginY={1}>
      <Box>
        <Text color={getMessageColor()} bold>
          {getMessagePrefix()}
        </Text>
        <Text color="gray" dimColor>
          [{formatTimestamp(message.timestamp)}]
        </Text>
      </Box>
      
      <Box marginLeft={2}>
        {/* 工具使用状态显示 */}
        {message.role === 'assistant' && message.status === 'sending' && (
          <ToolUsageIndicator theme={theme} />
        )}
        
        {/* 思考框显示 - 支持持久显示 */}
        {message.thinkingContent && (
          <ThinkingBox 
            thinkingContent={message.thinkingContent} 
            theme={theme} 
            isActive={message.isThinking && message.status === 'sending'}
            isPersistent={true}
          />
        )}
        
        {/* 显示正式回复内容 */}
        {message.content ? (
          message.role === 'assistant' ? (
            <MarkdownRenderer content={message.content} theme="dark" />
          ) : (
            <Text color={getMessageColor()}>{message.content}</Text>
          )
        ) : (
          message.status === 'sending' && !message.isThinking && (
            <Text color={getMessageColor()}>正在生成回复...</Text>
          )
        )}
        
        {/* 显示MCP工具调用结果 */}
        {message.toolCalls && message.toolCalls.length > 0 && (
          <Box marginTop={1}>
            <Text color="cyan" dimColor>
              🔧 使用了 {message.toolCalls.length} 个工具
            </Text>
          </Box>
        )}
      </Box>
      
      {(message.status === 'error' || message.status === 'interrupted') && (
        <Box marginLeft={2} marginTop={1}>
          <Text color={theme.errorMessage} dimColor>
            {message.status === 'interrupted' ? '⏹️ 消息已中断' : '❌ 消息发送失败'}
          </Text>
        </Box>
      )}
    </Box>
  );
};

export default MessageItem;